package com.itlong.cloud.app.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.DTO.app.old.AppOldRunLogDto;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.PO.AppUserProjectPO;
import com.itlong.cloud.POJO.PO.FeedbackInfoPO;
import com.itlong.cloud.POJO.PO.OperationLogPO;
import com.itlong.cloud.POJO.VO.app.old.AppOldAuthRelationVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppOldMineDao;
import com.itlong.cloud.app.dao.IAppOldRegisterDao;
import com.itlong.cloud.app.service.IAppOldMineService;
import com.itlong.cloud.app.service.IAppOldRegisterService;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.operate.dao.IOperateUserFeedbackDao;
import com.itlong.cloud.property.dao.IPropertyAppUserProjectDao;
import com.itlong.cloud.property.service.IPropertyHouseHoldInfoService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *     旧版APP的我版块服务层实现类
 * </desc>
 *
 * @createDate 2017/11/1
 */
@Service
public class AppOldMineServiceImpl implements IAppOldMineService {
    private static final Logger LOG = LoggerFactory.getLogger(AppOldMineServiceImpl.class);

    @Autowired
    IAppOldMineDao iAppOldMineDao;
    @Autowired
    IAppOldRegisterDao iAppOldRegisterDao;
    @Autowired
    IOperateUserFeedbackDao iOperateUserFeedbackDao;

    @Autowired
    IPropertyHouseHoldInfoService iPropertyHouseHoldInfoService;

    @Autowired
    IAppOldRegisterService iAppOldRegisterService;

    @Autowired
    IPropertyAppUserProjectDao iPropertyAppUserProjectDao;

    /**
     * <desc>
     *     旧版APP_邀请家人查询当前用户的业主房间信息
     * </desc>
     * @param userId
     * @param projectId
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/1
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public JSONObject getUserOwnRoom(String userId,String projectId){
        JSONObject js = new JSONObject();
        Map<String,Object> projectInfoMap = iAppOldMineDao.getProjectById(projectId);
        js.put("projectId",projectId);
        js.put("projectName",projectInfoMap.get("projectName").toString());
        JSONArray buildArr = new JSONArray();
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("projectId",projectId);
        params.put("houserType","1"); //业主本人
        List<Map<String,Object>> userBuildList = iAppOldMineDao.getUserOwnBuild(params);
        if (userBuildList != null&&userBuildList.size()>0){
            for (Map buildmap:userBuildList){
                JSONObject buildjs = new JSONObject();
                buildjs.put("buildId",buildmap.get("buildId").toString());
                buildjs.put("buildName",buildmap.get("buildName").toString());

                params.put("buildId",buildmap.get("buildId").toString());
                List<Map<String,Object>> userUnitList = iAppOldMineDao.getUserOwnUnit(params);
                JSONArray unitArr = new JSONArray();
                if (userUnitList != null&&userUnitList.size()>0){
                    for (Map unitmap:userUnitList){
                        JSONObject unitjs = new JSONObject();
                        unitjs.put("unitId",unitmap.get("unitId").toString());
                        unitjs.put("unitName",unitmap.get("unitName").toString());

                        JSONArray roomArr = new JSONArray();
                        params.put("unitId",unitmap.get("unitId").toString());
                        List<Map<String,Object>> userRoomList = iAppOldMineDao.getUserOwnRoom(params);
                        if (userRoomList != null&&userRoomList.size()>0){
                            for (Map roommap:userRoomList){
                                JSONObject roomjs = new JSONObject();
                                roomjs.put("roomNum",roommap.get("room_id").toString());
                                roomjs.put("roomName", StringHandlerUtil.getNullOrStringForObject(roommap.get("build_name"))
                                        +StringHandlerUtil.getNullOrStringForObject(roommap.get("unit_name"))
                                        +StringHandlerUtil.getNullOrStringForObject(roommap.get("room_num")));
                                roomArr.add(roomjs);
                            }
                        }
                        unitjs.put("roomArr",roomArr);
                        unitArr.add(unitjs);
                    }
                }
                buildjs.put("unitArr",unitArr);
                buildArr.add(buildjs);
            }
        }
        js.put("buildArr",buildArr);
        return  js;
    }

    /**
     * <desc>
     *     旧版APP_已授权家人列表
     * </desc>
     * @param projectId
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/2
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message getAuthPersionList(String projectId,String userId,Integer pageNo,Integer pageSize) throws Exception{
        Map<String,Object> params = new HashMap<>();
        params.put("projectId",projectId);
        params.put("parentUserId",userId);
        Page page = new Page();
        if (pageNo==0){
            pageNo=1;
        }
        if (pageSize <= 0){
            pageSize = 10;
        }
        page.getPage().setCurrentPage(pageNo+"");
        page.getPage().setPageSize(pageSize+"");
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        List<Map<String, Object>> appAuthRelationList = iAppOldMineDao.getChildUserByPage(params);
        List<AppOldAuthRelationVO> appOldAuthRelationVOList = new ArrayList<>();
        if (appAuthRelationList != null&&appAuthRelationList.size()>0){
            for (Map childmap:appAuthRelationList){
                AppOldAuthRelationVO appOldAuthRelationVO = new AppOldAuthRelationVO();
                if (childmap.get("phoneNo") != null&&StringUtils.isNotBlank(childmap.get("phoneNo").toString())){
                    appOldAuthRelationVO.setPhoneNo(childmap.get("phoneNo").toString());
                }
                if (childmap.get("userRemarks") != null&&StringUtils.isNotBlank(childmap.get("userRemarks").toString())){
                    appOldAuthRelationVO.setUserRemarks(childmap.get("userRemarks").toString());
                }
                if (childmap.get("createTime") != null){
                    appOldAuthRelationVO.setCreateTime(((Date) childmap.get("createTime")).getTime());
                }
                if (childmap.get("userName") != null&&StringUtils.isNotBlank(childmap.get("userName").toString())){
                    appOldAuthRelationVO.setUserName(childmap.get("userName").toString());
                }
                if (childmap.get("photoUrl") != null&&StringUtils.isNotBlank(childmap.get("photoUrl").toString())){
                    appOldAuthRelationVO.setPhotoUrl(childmap.get("photoUrl").toString());
                }
                StringBuffer addressInfo = new StringBuffer();
                if (childmap.get("projectName") != null&&StringUtils.isNotBlank(childmap.get("projectName").toString())){
                    addressInfo.append("{" + childmap.get("projectName").toString() + ",");
                }
                if (childmap.get("buildName") != null&&StringUtils.isNotBlank(childmap.get("buildName").toString())){
                    addressInfo.append(childmap.get("buildName").toString() + ",");
                }
                if (childmap.get("unitName") != null&&StringUtils.isNotBlank(childmap.get("unitName").toString())){
                    addressInfo.append(childmap.get("unitName").toString() + ",");
                }
                if (childmap.get("roomName") != null&&StringUtils.isNotBlank(childmap.get("roomName").toString())){
                    addressInfo.append(childmap.get("roomName").toString() + "}");
                }
                appOldAuthRelationVO.setAddressInfo(addressInfo.toString());
                appOldAuthRelationVO=(AppOldAuthRelationVO)StringHandlerUtil.formatString(appOldAuthRelationVO);
                appOldAuthRelationVOList.add(appOldAuthRelationVO);
            }
        }
        return  new Message(Code.SUCCESS,"",appOldAuthRelationVOList);
    }

    /**
     * <desc>
     *     旧版APP_修改授权人备注
     * </desc>
     * @param userId
     * @param authPhoneNo
     * @param userRemarks
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/2
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message updateAuthUserRemark(String userId,String authPhoneNo,String userRemarks) throws Exception{
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(authPhoneNo);
        Map<String,Object> params = new HashMap<>();
        params.put("userId",appOldUserInfoDto.getUserId());
        params.put("parentUserId",userId);
        params.put("userRemarks",userRemarks);
        int result = iAppOldMineDao.updateChildRemark(params);
        if (result>0){
            return  new Message(Code.SUCCESS);
        }else {
            return  new Message(Code.ERROR);
        }
    }
    /**
     * <desc>
     *     旧版APP_添加用户反馈信息
     * </desc>
     * @param userId
     * @param projectId
     * @param feedbackInfo
     * @return
     * @throws Exception
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/3
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message addFeekBack(String userId,String projectId,String feedbackInfo) throws Exception{
        FeedbackInfoPO feedbackInfoPO = new FeedbackInfoPO(userId,projectId,feedbackInfo,0,new Date());
        Integer result = iOperateUserFeedbackDao.save(SqlUtil.durableData(feedbackInfoPO, PlatformConstants.TABLE_SAVE));
        if (result>0){
            return  new Message(Code.SUCCESS);
        }else {
            return  new Message(Code.ERROR);
        }
    }
    /**
     * <desc>
     *     旧版APP_删除家人
     * </desc>
     * @param phoneNo
     * @param authPhoneNo
     * @param projectId
     * @return
     * @throws Exception
     * * @author cuiduanwu
     * @createDate 2017/11/2
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message delUserChild(String phoneNo,String authPhoneNo,String projectId) throws Exception{
        AppOldUserInfoDto parentUserDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        AppOldUserInfoDto childUserDto = iAppOldRegisterDao.selectDtoByPhone(authPhoneNo);
        if (parentUserDto == null||childUserDto == null){
            //LOG.info("【旧版APP_删除家人】"+"_parentPhone:"+phoneNo+"_childPhone:"+authPhoneNo+"--账号不存在");
            return  new Message(Code.NOT_FOUNDUSER);
        }
        Map<String,Object> params = new HashMap<>();
        params.put("userId",childUserDto.getUserId());
        params.put("parentUserId",parentUserDto.getUserId());
        if (StringUtils.isNotBlank(projectId)){
            params.put("projectId",projectId);
        }
        List<Map<String,Object>> childUserList = iAppOldMineDao.getAllChildUser(params);
        List<String> delRelationIds = new ArrayList<>(); //待删除的用户关系记录ID
        Set<String> projectSet = new HashSet<>();
        List<Integer> delUserRoomPkList = new ArrayList<>(); //待删除的用户房间记录ID

        if (childUserList != null&&childUserList.size()>0){
            for (Map map:childUserList){
                delRelationIds.add(map.get("id").toString());
                if (StringUtils.isNotBlank(map.get("projectId").toString())){
                    projectSet.add(map.get("projectId").toString());
                }
                if (StringUtils.isNotBlank(map.get("projectId").toString())&&StringUtils.isNotBlank(map.get("buildId").toString())&&StringUtils.isNotBlank(map.get("unitId").toString())&&StringUtils.isNotBlank(map.get("roomId").toString())){
                    map.put("userId",childUserDto.getUserId());
                    int userRoomPk = iAppOldMineDao.selectUserRoomPk(map);
                    if (userRoomPk !=0){
                        delUserRoomPkList.add(userRoomPk);
                    }
                }
            }
        }
        if (delRelationIds.size()>0){
            iAppOldMineDao.delUserRelationBatch(delRelationIds);
            //删除用户与房间的关系
            iAppOldMineDao.delUserRoomBatch(delUserRoomPkList);
        }
        if (projectSet != null&&projectSet.size()>0){
            List<String> changeUserList = new ArrayList<>();
            changeUserList.add(childUserDto.getUserId());
            for (String changeProjectId:projectSet){
                iPropertyHouseHoldInfoService.updateAppUserAuth(changeUserList,parentUserDto.getUserId(),changeProjectId);
            }
        }
        //TODO  通知云对讲设备更新指令



        //组装响应结果
        JSONObject js = iAppOldRegisterService.getUserProjectInfo(childUserDto.getUserId(),projectId);
        return new Message(Code.SUCCESS, js);
    }

    /**
     * <desc>
     *     旧版APP_获取所有正在服务中的小区信息，用户所拥有小区除外
     * </desc>
     * @param phoneNo
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/9
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message getServiceProject(String phoneNo) throws Exception{
        JSONArray jsArr = new JSONArray();
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return  new Message(Code.TOKEN_ERR);
        }
        List<Map<String,Object>> projectList = iAppOldMineDao.getServiceProject(appOldUserInfoDto.getUserId());
        if (projectList != null&&projectList.size()>0){
            for (Map projectmap:projectList){
                JSONObject js = new JSONObject();
                js.put("autoIndex",projectmap.get("id").toString());
                js.put("projectId",projectmap.get("projectId").toString());
                js.put("projectName",projectmap.get("projectName").toString());
                js.put("province","");
                js.put("city","");
                js.put("district","");
                jsArr.add(js);
            }
        }
        return new Message(Code.SUCCESS,jsArr);
    }
    /**
     * <desc>
     *      旧版APP_用户添加小区
     * </desc>
     * @param phoneNo
     * @param projectId
     * @param projectName
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/9
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message addProjectByUser(String phoneNo,String projectId,String projectName) throws Exception{
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return  new Message(Code.TOKEN_ERR);
        }
        Map<String,Object> params = new HashMap<>();
        params.put("userId",appOldUserInfoDto.getUserId());
        params.put("projectId",projectId);
        int result = iAppOldMineDao.checkUserProject(params);
        if (result>0){
            return new Message(Code.USER_PROJECT_EXIST);
        }else {
            AppUserProjectPO appUserProjectPO = new AppUserProjectPO(appOldUserInfoDto.getUserId(),projectId,"0","000000","1",1,1,new Date());
            Integer aupResult = iPropertyAppUserProjectDao.save(SqlUtil.durableData(appUserProjectPO, PlatformConstants.TABLE_SAVE));
            if (aupResult>0){
                //组装响应结果
                JSONObject js = iAppOldRegisterService.getUserProjectInfo(appOldUserInfoDto.getUserId(),"");
                return new Message(Code.SUCCESS, js);
            }else {
                return new Message(Code.ERROR);
            }
        }
    }

    /**
     * <desc>
     *     旧版APP_用户删除小区
     * </desc>
     * @param phoneNo
     * @param projectId
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message delProjectByUser(String phoneNo,String projectId) throws Exception{
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return  new Message(Code.TOKEN_ERR);
        }
        Integer result = iAppOldMineDao.delProjectByUser(appOldUserInfoDto.getUserId(),projectId);
        if (result>0){
            return new Message(Code.SUCCESS);
        }else {
            return new Message(Code.ERROR);
        }
    }





    /**
     * <desc>
     *     旧版APP_用户点击切换小区
     * </desc>
     * @param phoneNo
     * @param projectId
     * @param projectName
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message userChangeProject(String phoneNo,String projectId,String projectName) throws Exception{





        return  null;
    }


    /**
     * <desc>
     *     旧版APP_运行日志上传
     * </desc>
     * @param logJson
     * @return
     * @throws Exception
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message addRunLog(String logJson) throws Exception{
        List<AppOldRunLogDto> runs =  null;
        try {
            runs = JSONArray.parseObject(logJson,new TypeReference<List<AppOldRunLogDto>>(){});
        } catch (Exception e) {
            LOG.error("【旧版APP_运行日志上传】旧版APP运行日志转换失败", e);
            return new Message(Code.PARAM_ERR);
        }
        List<OperationLogPO> operationLogPOList = new ArrayList<>();
        String logContent = "";
        if (runs != null&&runs.size()>0){
            Date now = new Date();
            for (AppOldRunLogDto appOldRunLogDto:runs){
                logContent = appOldRunLogDto.getLogInfo();
                if (logContent.length()>3500){
                    logContent = logContent.substring(logContent.length()-3500,logContent.length());
                }
                OperationLogPO operationLogPO = new OperationLogPO(appOldRunLogDto.getPhoneNo(),appOldRunLogDto.getPhoneNo(),0,logContent);
                if ("iOS".equals(appOldRunLogDto.getLogSource())){
                    operationLogPO.setSystemType(3);
                }else if ("Android".equals(appOldRunLogDto.getLogSource())){
                    operationLogPO.setSystemType(4);
                }else {
                    operationLogPO.setSystemType(4);
                }
                operationLogPO.setStatus(1);
                operationLogPO.setCreateTime(now);
                operationLogPOList.add(operationLogPO);
            }
        }
        if (operationLogPOList != null&&operationLogPOList.size()>0){
            iAppOldMineDao.saveRunLogBatch(operationLogPOList);
        }
        return  new Message(Code.SUCCESS);
    }





































}
